package com.zzp.basepresenter.ui.popwindows;

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.zzp.basepresenter.R;

public abstract class BasePopupWindow extends PopupWindow {
    public Activity context;

    //set contentView
    public abstract int getResView();

    //background is transparent?
    public abstract boolean transparentBackground();

    //touch out side is hide?
    public abstract boolean outTouchNotHide();

    //bind view plugin
    public abstract void findViewById(View view);

    //set view width
    public abstract int setWidth();

    //set view height
    public abstract int setHeight();

    //set view AnimationStyle  -1 不设置动画  0 默认动画  other 自定义动画
    public abstract int setAnimationStyle();

    //show popwindow
    public abstract void show(Activity context, View view);

    public BasePopupWindow(Activity context) {
        super(context);
        this.context = context;
        View view = LayoutInflater.from(context).inflate(getResView(), null);
        setContentView(view);
        findViewById(view);
        //设置宽度
        setWidth(setWidth() == 0 ? ViewGroup.LayoutParams.WRAP_CONTENT : setWidth());
        //设置高度
        setHeight(setHeight() == 0 ? ViewGroup.LayoutParams.WRAP_CONTENT : setHeight());
        if (setAnimationStyle() != -1) {
            //设置显示隐藏动画
            setAnimationStyle(setAnimationStyle() == 0 ? R.style.take_photo_anim : setAnimationStyle());
        }
        //设置背景透明
        setBackgroundDrawable(new ColorDrawable(127));
        //监听窗口的焦点事件，点击窗口外面则取消显示
        view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && !outTouchNotHide()) {
                    dismiss();
                }
            }
        });
        this.setOutsideTouchable(!outTouchNotHide());
        //设置默认获取焦点
        this.setFocusable(!outTouchNotHide());
    }

    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        super.showAtLocation(parent, gravity, x, y);
        if (!transparentBackground()) {
            bgAlpha(0.6f);
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (!transparentBackground()) {
            bgAlpha(1.0f);
        }
    }

    /**
     * 设置窗口的背景透明度
     *
     * @param f 0.0-1.0
     */
    private void bgAlpha(float f) {
        WindowManager.LayoutParams layoutParams = context.getWindow().getAttributes();
        layoutParams.alpha = f;
        context.getWindow().setAttributes(layoutParams);
    }
}
